import styles from './home.less';
import React, { useState, useRef, useEffect } from 'react';
import { treeData, columns } from './contant';
import { Tree, Button, Input, message, Table } from 'antd';
import _ from 'lodash';
import PropTypes from 'prop-types';
const { TreeNode } = Tree;
const { Search } = Input;
const Title = ({ title, changeTitle }) => {
    const [isEdit, setIsEdit] = useState(false);
    const inputRef = useRef(null);
    const [inputV, setInputV] = useState(title);

    const changeEdit = (isBlur) => {
        setIsEdit(!isEdit);
        if (isBlur) {
            changeTitle(inputV);
        }
    };

    // 获取焦点
    useEffect(() => {
        if (isEdit) {
            inputRef.current.focus();
        }
    }, [isEdit]);

    const onChange = (e) => {
        let value = e.target.value;
        setInputV(value);
    };
    return (
        <div>
            {title}
            {
                isEdit ?
                    <Input ref={inputRef} value={inputV} onChange={onChange} onBlur={() => { changeEdit(true); }} /> :
                    <Button onClick={() => { changeEdit(false); }} style={{ marginLeft: 20 }}>修改</Button>
            }
        </div>
    );
};

Title.propTypes = {
    title: PropTypes.string,
    changeTitle: PropTypes.func
};

const Home = () => {
    const [tree, setTree] = useState([...treeData]);
    const [expandedKeys, setExpandedKeys] = useState([]);
    const [flatTree, setFlatTree] = useState([]);
    const flag = useRef(false);
    const changeTitle = (value, curKey) => {
        let copyTree = [...tree];
        const findNode = (nodes) => {
            nodes.some(item => {
                if (item.key === curKey) {
                    item.title = value;
                    setTree(copyTree);
                    return true;
                }
                if (item.children && item.children.length) {
                    findNode(item.children);
                }
            });
        };
        findNode(copyTree);
    };

    const getSearchResult = (node, search) => {
        let isSearchPass;
        if (node.title) {
            if (search) {
                isSearchPass = node.title.indexOf(search) !== -1  ? true : false;
            } else {
                isSearchPass = false;
            }
        } else {
            isSearchPass = false;
        }
        return isSearchPass;
    };

    useEffect(() => {
        if (flag.current) {
            message.success('数据变化回调');
        }
        flag.current = true;
    }, [tree]);
    const doTreeFilter = (data, filterFn, allKeys = []) => {
        function doFilter(data) {
            return data.filter(function(d) {
                var childflag = false;
                if (d.children && d.children.length) {
                    d.children = doFilter(d.children);
                    if (d.children.length) {
                        childflag = true;
                    }
                }
                var flag = filterFn(d);
                if (flag) {
                    allKeys.push(d.key);
                    return true;
                } else if (childflag) {
                    allKeys.push(d.key);
                    return true;
                }
                return false;
            });
        }
        doFilter(data);
        return allKeys;
    };

    const onSearch = value => {
        if (!value) {
            message.info('请输入查询内容');
        }
        let data = _.cloneDeep(tree);
        let allKeys = []; 
        allKeys = doTreeFilter(data, (item) => {
            var searchResult = getSearchResult(item, value);
            if (!searchResult) {
                return false;
            }
            return true;
        });
        setExpandedKeys(allKeys);
    };

    const loop = (data) => {
        return data.map(item => {
            let curKey = item.key;
            if (item.children && item.children.length) {
                return (
                    <TreeNode key={curKey} title={<Title title={item.title} changeTitle={(v) => { changeTitle(v, curKey); }} />}>
                        {loop(item.children)}
                    </TreeNode>
                );
            }
            return <TreeNode key={curKey} title={<Title title={item.title} changeTitle={(v) => { changeTitle(v, curKey); }} />} />;
        });
    };

    const getJson = (data) => {
        return data.reduce((pre, { title, key, children = [] }) => {
            return pre.concat([{ title, key }], getJson(children));
        }, []);
    };
    return (
        <div className={styles.home}>
            <h1>``````</h1>
            <Search placeholder="输入title进行模糊查询" onSearch={onSearch} style={{ width: 340, margin: 20 }} />
            <Tree
                onExpand={(keys) => { setExpandedKeys(keys); }}
                expandedKeys={expandedKeys}
            >
                {
                    loop(tree)
                }
            </Tree>
            <div>
                <Button type="primary" onClick={() => { setFlatTree(tree); console.log(getJson(tree));}}>获取整棵树json</Button>
                <strong>（这个要求有点困惑，就按照我自己的理解来了，把这棵树拍扁, console可见）</strong>
            </div>
            {
                flatTree.length ? 
                    <Table dataSource={flatTree} columns={columns} pagination={false} />
                    : null
            }
        </div>
    );
};
export default Home;